package com.shigu.admin.manager.services;

import com.opentae.data.mall.beans.ManagerRole;
import com.opentae.data.mall.beans.ManagerUser;
import com.opentae.data.mall.beans.ManagerUserRole;
import com.opentae.data.mall.beans.UserRole;
import com.opentae.data.mall.examples.ManagerRoleExample;
import com.opentae.data.mall.examples.ManagerUserExample;
import com.opentae.data.mall.examples.ManagerUserRoleExample;
import com.opentae.data.mall.interfaces.ManagerRoleMapper;
import com.opentae.data.mall.interfaces.ManagerUserMapper;
import com.opentae.data.mall.interfaces.ManagerUserRoleMapper;
import com.shigu.admin.manager.common.CustomPager;
import com.shigu.admin.manager.utils.PageUtil;
import com.shigu.admin.manager.vo.UserRoleVO;
import com.shigu.admin.manager.vo.UserVO;
import com.shigu.component.shiro.CustomCredentialsMatcher;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户角色权限管理
 * Created by zhaohongbo on 16/5/12.
 */
@Service
public class AdminUserService {

    @Autowired
    ManagerUserMapper managerUserMapper;

    @Autowired
    ManagerRoleMapper managerRoleMapper;

    @Autowired
    ManagerUserRoleMapper managerUserRoleMapper;

    /**
     * 按Id拿一个用户信息
     * @param uid
     * @return
     */
    public UserVO seluserByid(Long uid){
        ManagerUser user= managerUserMapper.selectByPrimaryKey(uid);
        if(user==null){
            return null;
        }
        UserVO uv=new UserVO();
        uv.setStatus(user.getStatus());
        uv.setUserId(user.getUserId());
        uv.setCreateTime(user.getCreateTime());
        uv.setNick(user.getNick());
        uv.setUserName(user.getLoginName());
        return uv;
    }
    /**
     * 修改用户状态
     * @param uid
     * @return
     */
    @RequiresPermissions("user:modify")
    public int changeUserStatus(Long uid){
        ManagerUser user=managerUserMapper.selectByPrimaryKey(uid);
        if(user==null){
            return 0;
        }
        user.setStatus((user.getStatus() + 1) % 2);
        managerUserMapper.updateByPrimaryKeySelective(user);
        return 1;
    }
    /**
     * 修改用户角色
     * @param uid
     * @param rid
     * @return
     */
    @RequiresPermissions("user:modify")
    public int changeRole(Long uid,Long rid){
        ManagerUserRoleExample example=new ManagerUserRoleExample();
        example.createCriteria().andUserIdEqualTo(uid).andRoleIdEqualTo(rid);
        List<ManagerUserRole> urlist=managerUserRoleMapper.selectByExample(example);
        if(urlist.size()>0){
            managerUserRoleMapper.deleteByExample(example);
            return 2;
        }else{
            ManagerUserRole mur=new ManagerUserRole();
            mur.setUserId(uid);
            mur.setRoleId(rid);
            mur.setCreateTime(new Date());
            managerUserRoleMapper.insertSelective(mur);
            return 1;
        }
    }

    /**
     * 查单个用户详情
     * @param uid
     * @return
     */
    public UserVO seluserByuid(Long uid){
        ManagerUser user=managerUserMapper.selectByPrimaryKey(uid);
        if(user!=null){
            UserVO uvo=new UserVO();
            uvo.setUserId(uid);
            uvo.setCreateTime(user.getCreateTime());
            uvo.setStatus(user.getStatus());
            uvo.setNick(user.getNick());
            return uvo;
        }
        return null;
    }
    /**
     * 修改密码
     * @param uid
     * @param password
     * @return
     */
    @RequiresPermissions(value = {"user:list","system:mypwd"},logical = Logical.OR)
    public int modpwd(Long uid,String password){
        ManagerUser user=new ManagerUser();
        user.setUserId(uid);
        user.setPassword(CustomCredentialsMatcher.encrypt(password));
        return managerUserMapper.updateByPrimaryKeySelective(user);
    }
    /**
     * 查出所有角色列表
     * @param userId
     * @return
     */
    @RequiresPermissions("user:modify")
    public List<UserRoleVO> selRoleAll(Long userId){
        ManagerRoleExample mrexam=new ManagerRoleExample();
        mrexam.createCriteria().andStatusEqualTo(1);
        List<ManagerRole> list=managerRoleMapper.selectByExample(mrexam);
        List<Long> ridlist=new ArrayList<Long>();

        if(userId!=null){
            ManagerUserRoleExample example=new ManagerUserRoleExample();
            example.createCriteria().andUserIdEqualTo(userId);
            List<ManagerUserRole> urlist=managerUserRoleMapper.selectByExample(example);
            for(ManagerUserRole mur:urlist){
                ridlist.add(mur.getRoleId());
            }
        }
        List<UserRoleVO> uvlist=new ArrayList<UserRoleVO>();
        for(ManagerRole mr:list){
            UserRoleVO urv=new UserRoleVO();
            urv.setRoleComment(mr.getRoleComment());
            urv.setRoleName(mr.getRoleName());
            urv.setRoleId(mr.getRoleId());
            if(userId!=null&&ridlist.contains(mr.getRoleId())){
                urv.setUserId(userId);
            }
            uvlist.add(urv);
        }
        return uvlist;
    }

    /**
     * 检测已经注册过的关键词
     * @param nick
     * @param username
     * @return
     */
    @RequiresPermissions("user:add")
    public List<ManagerUser> checkNameAndNick(String nick,String username){
        if(nick==null&&username==null){
            return new ArrayList<ManagerUser>();
        }
        ManagerUserExample example=new ManagerUserExample();
        if(nick!=null){
            example.createCriteria().andNickEqualTo(nick);
            if(username!=null){
                example.or().andLoginNameEqualTo(username);
            }
        }else if(username!=null){
            example.createCriteria().andLoginNameEqualTo(username);
        }
        return managerUserMapper.selectByExample(example);
    }

    /**
     * 添加用户
     * @param nick
     * @param username
     * @param password
     * @return
     */
    @RequiresPermissions("user:add")
    public Long addUser(String nick,String username,String password){
        ManagerUser user=new ManagerUser();
        user.setNick(nick);
        user.setCreateTime(new Date());
        user.setLoginName(username);
        user.setPassword(CustomCredentialsMatcher.encrypt(password));
         managerUserMapper.insertSelective(user);
        return user.getUserId();
    }
    /**
     * 查用户
     * @return
     */
    @RequiresPermissions(value = {"user:list","user:modify"},logical = Logical.OR)
    public CustomPager<UserVO> selUsers(String userName,Integer pageNo,Integer pageSize,Integer status){
        ManagerUserExample example=new ManagerUserExample();
        example.setOrderByClause("user_id desc");
        if(userName!=null){
            if(status!=null){
                example.createCriteria().andLoginNameLike("%"+userName+"%").andStatusEqualTo(status);
                example.or().andNickLike("%"+userName+"%").andStatusEqualTo(status);
            }else {
                example.createCriteria().andLoginNameLike("%"+userName+"%");
                example.or().andNickLike("%"+userName+"%");
            }
        }else if(status!=null){
            example.createCriteria().andStatusEqualTo(status);
        }
        example.setStartIndex((pageNo - 1) * pageSize);
        example.setEndIndex(pageSize);
        int total=managerUserMapper.countByExample(example);
        List<ManagerUser> mulist=managerUserMapper.selectByConditionList(example);
        Map<Long,UserVO> vomap=new HashMap<Long, UserVO>();
        String userIds="";
        for(ManagerUser mu:mulist){
            userIds+=","+mu.getUserId();
            UserVO uv=new UserVO();
            uv.setUserId(mu.getUserId());
            uv.setCreateTime(mu.getCreateTime());
            uv.setNick(mu.getNick());
            uv.setStatus(mu.getStatus());
            uv.setUserName(mu.getLoginName());
            uv.setRoleNames(new ArrayList<UserRole>());
            vomap.put(mu.getUserId(),uv);
        }
        if(userIds.length()>0){
            userIds=userIds.substring(1);
        }
        List<UserRole> roleList=new ArrayList<UserRole>();
        if(!userIds.equals("")){
            roleList=managerRoleMapper.selRoleNamesByuserIds(userIds);
        }
        for(UserRole ur:roleList){
            UserVO uv=vomap.get(ur.getUserId());
            List<UserRole> roles=uv.getRoleNames();
            roles.add(ur);
        }
        CustomPager<UserVO> pager=new CustomPager<UserVO>();
        List<UserVO> userlist=new ArrayList<UserVO>();
        userlist.addAll(vomap.values());
        pager.setNumber(pageNo-1);
        pager.setTotalPages(PageUtil.calPage(pageSize, total));
        pager.setContent(userlist);
        return pager;
    }


}
